var DGNModel           = require('./DGNModel');
var DGNProto           = require('./DGNProto');
var RoomProto         = require('../../API/RoomProto');
var HallApi           = require('../../API/HallAPI');
var RoomAPI           = require('../../API/RoomAPI');
var RoomMessageRouter = 'game.gameHandler.roomMessageNotify';
var GameMessageRouter = 'game.gameHandler.gameMessageNotify';

cc.Class({
	extends: cc.Component,
	properties: {
	},

	onLoad: function () {
		this.seatNames = ['北京', '上海', '广州', '天津', '重庆', '香港', '南京', '澳门', '海口', '深圳'];
		this.msgbg = cc.find('msgbg', this.node);
		this.headSprite = cc.find('head', this.node).getComponent(cc.Sprite);
		this.nameLabel = cc.find('name', this.node).getComponent(cc.Label);
		this.idLabel = cc.find('id', this.node).getComponent(cc.Label);
		this.robSprite = cc.find('robstate', this.node).getComponent(cc.Sprite);
		this.scoreNode = cc.find('scorebg', this.node);
		this.scoreNode2 = cc.find('BankerScorePool', this.node);
		this.scoreLabel = cc.find('scorebg/gold', this.node).getComponent(cc.Label);
		this.goldNode = cc.find('scorebg/icon', this.node);
		this.bankerNode = cc.find('banker', this.node);
		this.light = this.node.getChildByName('light');
		this.readyNode = this.node.getChildByName('ready');
		this.fangzhuNode = this.node.getChildByName('fangzhu');
		this.node.active = false;
		this.readyNodePos = this.readyNode.getPosition();
		this.scoreNodePos = this.scoreNode.getPosition();
		this.scoreNodePos2 = this.scoreNode2.getPosition();
		this.rangCircle = 30;

		Global.MessageCallback.addListener('RoomMessagePush', this);
		Global.MessageCallback.addListener('GameMessagePush', this);
		Global.MessageCallback.addListener('ReConnectSuccess', this);
	},

	setIndex: function (index) {
		this.index = index;
		if (this.index == 0 && cc.visibleRect.width/cc.visibleRect.height > 1.8) {
			this.readyNode.x = cc.visibleRect.width/2-1334/2+this.readyNodePos.x;
			this.scoreNode.x = cc.visibleRect.width/2-1334/2+this.scoreNodePos.x;
			this.scoreNode2.x = cc.visibleRect.width/2-1334/2+this.scoreNodePos2.x;
		}
	},

	showSeat: function () {
		let names = ['msgbg', 'head', 'headedg', 'fangzhu', 'name', 'id', 'scorebg', "BankerScorePool", 'banker', 'winscore', 'losescore', 'BankerScorePool/winscore', 'BankerScorePool/losescore', 'light', 'text', 'ready', 'offline'];
		for (let name of names) {
			let node = this.node.getChildByName(name);
			if (node) { node.active = false; }
		}
		this.refrushName();
	},

	hideSeat: function () {
		if (this.seatNode) {
			this.seatNode.active = false;
		}
		let names = ['head', 'headedg', 'name', 'id'];
		for (let name of names) {
			let node = this.node.getChildByName(name);
			if (node) {
				node.active = true;
			}
		}
	},

	refrushName: function () {
		if (!this.seatNode) {
			let node = new cc.Node();
			node.setPosition(this.msgbg.getPosition()); 
			node.parent = this.node;  

			let bgNode = new cc.Node();
			bgNode.parent = node;
			cc.loader.loadRes('Game/Common/citybg', cc.SpriteFrame, (err, spriteFrame) => {
				if (!err) {
					bgNode.addComponent(cc.Sprite).spriteFrame = spriteFrame;
					if (this.msgbg.width > this.msgbg.height) {
						bgNode.rotation = 90;
						bgNode.width = this.msgbg.height;
						bgNode.height = this.msgbg.width;
					}
					else {
						bgNode.height = this.msgbg.height;
						bgNode.width = this.msgbg.width;
					}
				}
			});
			let labelNode = new cc.Node();
			labelNode.color = new cc.Color(255, 255, 255);
			labelNode.name = 'Label'; 
			labelNode.parent = node;
			labelNode.y = 10;
			let label = labelNode.addComponent(cc.Label);
			label.fontSize = 25;
			label.string = this.seatNames[this.getChairID()];     

			bgNode.on(cc.Node.EventType.TOUCH_END, this.onSeatClick.bind(this), this); 
			this.seatNode = node;

			let arrow = new cc.Node();
			arrow.parent = node;
			arrow.y = -15;
			cc.loader.loadRes('Game/Common/jiantou', cc.SpriteFrame, (err, spriteFrame) => {
				if (!err) { arrow.addComponent(cc.Sprite).spriteFrame = spriteFrame; }
			});
			arrow.setScale(0.8);
		}
		else {
			this.seatNode.active = true;
			cc.find('Label', this.seatNode).getComponent(cc.Label).string = this.seatNames[this.getChairID()];  
		}
	},

	onSeatClick: function () {
		if (DGNModel.isUnionCreate()) {
			let user = DGNModel.getUserByChairID(DGNModel.getMyChairID());
			if (user.userInfo.score < DGNModel.getGameRule().scoreLowLimit) {
				Global.DialogManager.addTipDialog('金币不足，不能入座');
				return;
			}
		}
		Global.NetworkManager.notify(RoomMessageRouter, RoomProto.getUserChangeSeatNotify(DGNModel.getMyChairID(), this.getChairID()));
	},

	getChairID: function (chairID) {
		if (DGNModel.getMyChairID() >= DGNModel.getChairCount()) {
			return this.index;
		}
		else {
			return (DGNModel.getMyChairID()+this.index)%DGNModel.getChairCount();
		}
	},

	gameInit: function () {
		if (typeof(this.index) != 'number') { return; } /* 未使用，等待销毁 */ 
		this.node.active = true;
		let user = DGNModel.getUserByChairID(this.getChairID());
		if (!user) {
			let ready = (DGNModel.getUserByChairID(DGNModel.getMyChairID()).userStatus&RoomProto.userStatusEnum.READY);
			if ((DGNModel.getCurBureau() == 0 && !ready) || (DGNModel.getMyChairID() >= DGNModel.getChairCount() && DGNModel.getGameRule().canEnter)) {
				this.showSeat();
			}
			else {
				/* this.hideSeat(); */
				this.node.active = false;
			}
			return;
		}
		else {
			this.hideSeat();
		}

		this.nameLabel.string = user.userInfo.nickname;
		this.idLabel.string = DGNModel.getCurScore(this.getChairID());
		this.fangzhuNode.active = false;
		Global.CCHelper.updateSpriteFrame(user.userInfo.avatar, this.headSprite);

		if (DGNModel.getGameStatus() == DGNProto.gameStatus.NONE) {
			this.readyNode.active = (user.userStatus&RoomProto.userStatusEnum.READY);
		}
		else if (DGNModel.getGameStatus() == DGNProto.gameStatus.CHOOSE_BANK) {
			this.readyNode.active = false;
		}
		else if (DGNModel.getGameStatus() >= DGNProto.gameStatus.SEND_CARDS) {
			this.readyNode.active = false;
		}
		this.setPourScore(DGNModel.getPourScoreByChairID(this.getChairID()));
		this.bankerNode.active = (this.getChairID() == DGNModel.getBankerChairID());
		/* this.showResultScore(); */
		cc.find('offline', this.node).active = (user.userStatus&RoomProto.userStatusEnum.OFFLINE) > 0;
	},

	/*
	 * 设置下分
	 */
	setPourScore: function (score, animal) {
		this.scoreNode.active = false;
		this.scoreNode2.active = false;
		if (score != null && score > 0) {
			if (this.getChairID() != DGNModel.getBankerChairID()) {
				this.scoreLabel.string = score;
				this.scoreNode.active = true;
				if (animal) {
					let icon = cc.find('scorebg/icon', this.node);
					let icon_pos = icon.getPosition();
					let end_pos = cc.v2(this.scoreNodePos.x+icon_pos.x, this.scoreNodePos.y+icon_pos.y);
					Global.AudioManager.playSound('Game/Niuniu/NNAudio/fly_gold');
					for (let i = 0; i < 5; ++i) {
						let node = cc.instantiate(icon);
						node.parent = this.node;
						node.x = this.rangCircle*2*Math.random()-this.rangCircle;
						node.y = this.rangCircle*2*Math.random()-this.rangCircle;
						node.opacity = 0;
						node.runAction(cc.sequence(
							cc.fadeIn(0.08*i),
							cc.moveTo(0.3, end_pos),
							cc.removeSelf()
						));
					}
				}
			}
			else {
				this.scoreNode2.active = true;
				cc.find("Label", this.scoreNode2).getComponent(cc.Label).string = ""+score;
				if (animal) {
					let icon = cc.find('scorebg/icon', this.node);
					let end_pos = cc.v2(this.scoreNodePos2.x+icon_pos.x, this.scoreNodePos2.y+icon_pos.y);
					Global.AudioManager.playSound('Game/Niuniu/NNAudio/fly_gold');
					for (let i = 0; i < 10; ++i) {
						let node = cc.instantiate(icon);
						/* node.setPosition(0, 0); */
						node.x = this.rangCircle*2*Math.random()-this.rangCircle;
						node.y = this.rangCircle*2*Math.random()-this.rangCircle;
						node.parent = this.node;
						node.opacity = 0;
						node.runAction(cc.sequence(
							cc.fadeIn(0.08*i), 
							cc.moveTo(0.3, end_pos),
							cc.removeSelf()
						));
					}

				}
			}
		}
		if (DGNModel.getCurBureau() >= 1) {
			if (DGNModel.getBankerChairID() == null) {
				this.scoreNode2.active = true;
				cc.find("Label", this.scoreNode2).getComponent(cc.Label).string = "0";
			}
			else if (DGNModel.getBankerChairID() == this.getChairID()){
				this.scoreNode2.active = true;
				cc.find("Label", this.scoreNode2).getComponent(cc.Label).string = ""+score;
			}
		}
	},

	messageCallbackHandler: function(router, msg) {
		if(!DGNModel.getGameInited()) { return; }
		if (router === 'RoomMessagePush') {
			if(msg.type === RoomProto.GET_ROOM_SCENE_INFO_PUSH) {
				this.gameInit();
			}
			else if(msg.type === RoomProto.USER_READY_PUSH) {
				if (msg.data.chairID == DGNModel.getMyChairID() && DGNModel.getCurBureau() == 0) {
					this.gameInit();
				}
				if (this.node.active && msg.data.chairID == this.getChairID()) {
					this.readyNode.active = true;
					this.scoreNode.active = false;
				}
				if (this.node.active && (msg.data.chairID == DGNModel.getMyChairID())) {
					let user = DGNModel.getUserByChairID(this.getChairID());
					if (user) {
						this.scoreNode.active = false;
						this.readyNode.active = (user.userStatus&RoomProto.userStatusEnum.READY);
						this.bankerNode.active = (DGNModel.getBankerChairID() == this.getChairID());
						cc.find("winscore", this.node).active = false;
						cc.find("losescore", this.node).active = false;
						cc.find("BankerScorePool/winscore", this.node).active = false;
						cc.find("BankerScorePool/losescore", this.node).active = false;
					}
				}
			}
			else if(msg.type === RoomProto.USER_LEAVE_ROOM_RESPONSE) {
				/* if(msg.data.chairID == this.getChairID()) {
					this.node.active = false;
				} */
			}
			else if(msg.type === RoomProto.OTHER_USER_ENTRY_ROOM_PUSH) {
				if (msg.data.roomUserInfo.chairID == this.getChairID()) {
					this.gameInit();
				}
			}
			else if(msg.type === RoomProto.USER_LEAVE_ROOM_PUSH) {
				if (msg.data.roomUserInfo.chairID == this.getChairID()) {
					this.node.active = false;
				}
			}
			else if(msg.type === RoomProto.USER_CHANGE_SEAT_PUSH) {
				if (DGNModel.getCurBureau() == 0) {
					this.gameInit();
				}
				else {
					if (DGNModel.getMyUid() != msg.data.uid) {
						if (this.getChairID() == msg.data.fromChairID || this.getChairID() == msg.data.toChairID) {
							this.gameInit();
						}
					}
					else {
						this.gameInit();
					}
				}
			}
			else if(msg.type === RoomProto.ROOM_USER_INFO_CHANGE_PUSH) {
				let user = DGNModel.getUserByChairID(this.getChairID());
				if (this.node.active && user) {
					/* this.idLabel.string = Math.floor(user.userInfo.score); */
					this.idLabel.string = DGNModel.getCurScore(this.getChairID());
				}
			}
			else if(msg.type === RoomProto.USER_OFF_LINE_PUSH) {
				if (msg.data.chairID == this.getChairID()) {
					cc.find('offline', this.node).active = true;
				}
			}
		}
		else if(router === 'GameMessagePush') {
			if(msg.type === DGNProto.BANKER_PUSH) {
				this.setBanker(msg.data.bankerChairID);
				if (msg.data.bankerChairID == this.getChairID()) {
					this.bankerPour();
				}
			}
			else if(msg.type === DGNProto.CLEAR_POOL_PUSH) {
				if (msg.data.bankerChairID == this.getChairID()) {
					this.bankerClearGold();
					this.setPourScore(0);
				}
			}
			else if(msg.type === DGNProto.POUR_SCORE_PUSH) {
				if (msg.data.chairID == this.getChairID()) {
					this.setPourScore(msg.data.score, true);
					this.idLabel.string = DGNModel.getCurScore(this.getChairID());
				}
			}
			else if(msg.type === DGNProto.GAME_STATUS_PUSH) {
				this.gameInit();
			}
			else if(msg.type === DGNProto.GAME_RESULT_PUSH) {
				if (DGNModel.getUserByChairID(this.getChairID())) {
					this.showResultScore(msg.data.result.winScores, true);
					this.idLabel.string = DGNModel.getCurScore(this.getChairID());
				}
			}
			else if(msg.type === DGNProto.GAME_CHAT_PUSH) {
				this.gameChat(msg.data);
			}
		} 
	},

	setBanker: function (bankerChairID) {
		this.bankerNode.active = (bankerChairID == this.getChairID());
	},

	showResultScore: function (winScores, animal) {
		cc.find("winscore", this.node).active = false;
		cc.find("losescore", this.node).active = false;
		cc.find("BankerScorePool/winscore", this.node).active = false;
		cc.find("BankerScorePool/losescore", this.node).active = false;
		let score = Math.floor(winScores[this.getChairID()]);
		var bankerChairID = DGNModel.getBankerChairID();
		if (bankerChairID != this.getChairID()) {
			if (score >= 0) {
				cc.find("winscore", this.node).active = true;
				cc.find("winscore", this.node).getComponent(cc.Label).string = '+' + Math.floor(score);
				if (animal) {
					cc.find("winscore", this.node).x = -50;
					cc.find("winscore", this.node).runAction(cc.moveTo(0.2, cc.v2(0, 22)).easing(cc.easeIn(3.0)));
				}
			}
			else if(score < 0) {
				cc.find("losescore", this.node).active = true;
				cc.find("losescore", this.node).getComponent(cc.Label).string = ''+Math.floor(score); 
				if (animal) {
					cc.find("losescore", this.node).x = -50;
					cc.find("losescore", this.node).runAction(cc.moveTo(0.2, cc.v2(0, 22)).easing(cc.easeIn(3.0)));
				}
			}
		}
		else {
			if (score >= 0) {
				cc.find("BankerScorePool/winscore", this.node).active = true;
				cc.find("BankerScorePool/winscore", this.node).getComponent(cc.Label).string = '+' + Math.floor(score);
				if (animal) {
					cc.find("BankerScorePool/winscore", this.node).y = 0;
					cc.find("BankerScorePool/winscore", this.node).runAction(cc.moveTo(0.2, cc.v2(0, 105)).easing(cc.easeIn(3.0)));
				}
			}
			else if(score < 0) {
				cc.find("BankerScorePool/losescore", this.node).active = true;
				cc.find("BankerScorePool/losescore", this.node).getComponent(cc.Label).string = ''+Math.floor(score); 
				if (animal) {
					cc.find("BankerScorePool/losescore", this.node).y = 0;
					cc.find("BankerScorePool/losescore", this.node).runAction(cc.moveTo(0.2, cc.v2(0, 105)).easing(cc.easeIn(3.0)));
				}
			}
		}
		if (bankerChairID != this.getChairID()) {
			if (score > 0) {
				this.scheduleOnce(() => { /* 庄家赔付 */ 
					this.goldMove(bankerChairID, this.getChairID());
				}, 1);
			}
			else {
				this.scheduleOnce(() => { /* 赔付庄家 */ 
					this.goldMove(this.getChairID(), bankerChairID);
				}, 0.5);
			}
		}
	},

	/*
	 * 获取其他头像相对于自己头像的位置
	 * @param Number chairID 其他头像的chairID
	 */
	getHeadNodePosByChairID: function (chairID) {
		if (chairID == this.getChairID()) {
			return cc.v2(0, 0);
		}
		else {
			return this.scoreNode2.getPosition();
		}
	},

	/*
	 * 结算时金币移动
	 * @param Number startChairID 开始的头像chairID
	 * @param Number endChairID 结束的头像chairID
	 */
	goldMove: function (startChairID, endChairID) {
		let speed = 1600;
		let startPos = this.getHeadNodePosByChairID(startChairID);
		let endPos = this.getHeadNodePosByChairID(endChairID);
		let distance = Math.sqrt(Math.pow(startPos.x-endPos.x, 2)+Math.pow(startPos.y-endPos.y, 2));
		let dt = distance/speed;

		let callFunc = cc.callFunc(() => {
			Global.AudioManager.playSound('Game/Niuniu/NNAudio/xiazhu');
		});
		for (let i = 0; i < 10; ++i) {
			let icon = cc.find('scorebg/icon', this.node);
			let gold = cc.instantiate(icon);
			gold.parent = this.node;
			/* gold.setPosition(startPos); */
			gold.x = startPos.x+this.rangCircle*2*Math.random()-this.rangCircle;
			gold.y = startPos.y+this.rangCircle*Math.random()-this.rangCircle;
			gold.opacity = 0;
			gold.runAction(cc.sequence(
				cc.fadeIn(0.08*i),
				cc.moveTo(dt, endPos),
				callFunc,
				cc.removeSelf()
			));
		}
	},

	bankerPour: function () {
		let speed = 1600;
		let startPos = this.msgbg.getPosition();
		let endPos = this.scoreNode2.getPosition();
		let distance = Math.sqrt(Math.pow(startPos.x-endPos.x, 2)+Math.pow(startPos.y-endPos.y, 2));
		let dt = distance/speed;
		let callFunc = cc.callFunc(() => {
			Global.AudioManager.playSound('Game/Niuniu/NNAudio/xiazhu');
		});
		for (let i = 0; i < 10; ++i) {
			let icon = cc.find('scorebg/icon', this.node);
			let gold = cc.instantiate(icon);
			gold.parent = this.node;
			/* gold.setPosition(startPos); */
			gold.x = startPos.x+this.rangCircle*2*Math.random()-this.rangCircle;
			gold.y = startPos.y+this.rangCircle*2*Math.random()-this.rangCircle;
			gold.opacity = 0;
			gold.runAction(cc.sequence(
				cc.fadeIn(0.08*i),
				cc.moveTo(dt, endPos),
				callFunc,
				cc.removeSelf()
			));
		}
	},

	bankerClearGold: function () {
		let speed = 1600;
		let endPos = this.msgbg.getPosition();
		let startPos = this.scoreNode2.getPosition();
		let distance = Math.sqrt(Math.pow(startPos.x-endPos.x, 2)+Math.pow(startPos.y-endPos.y, 2));
		let dt = distance/speed;
		let callFunc = cc.callFunc(() => {
			Global.AudioManager.playSound('Game/Niuniu/NNAudio/xiazhu');
		});
		for (let i = 0; i < 10; ++i) {
			let icon = cc.find('scorebg/icon', this.node);
			let gold = cc.instantiate(icon);
			gold.parent = this.node;
			/* gold.setPosition(startPos); */
			gold.x = startPos.x+this.rangCircle*2*Math.random()-this.rangCircle;
			gold.y = startPos.y+this.rangCircle*2*Math.random()-this.rangCircle;
			gold.opacity = 0;
			gold.runAction(cc.sequence(
				cc.fadeIn(0.08*i),
				cc.moveTo(dt, endPos),
				callFunc,
				cc.removeSelf()
			));
		}
	},

	/*
	 * 游戏聊天
	 */
	gameChat: function (data) {
		let node = cc.find('text', this.node);
		let label = cc.find('Label', node);
		if (data.chairID == this.getChairID()) {
			let user = DGNModel.getUserByChairID(this.getChairID());
			if (cc.find('emotion', node)) {
				cc.find('emotion', node).destroy();
			}
			if (data.type == 1) {
				label.active = false;
				let emotionNode = Global.CCHelper.getChatEmotionNode(data.msg, () => { node.active = false; });
				emotionNode.parent = node;
				emotionNode.setPosition(-70, 0);
				emotionNode.scaleX = node.scaleX;
				emotionNode.name = 'emotion';
				node.setContentSize(130, 110);
				node.active = true;
			}
			else if(data.type == 2) {
				let index = ['快点啊，等到花儿都谢了！', '不要吵了，不要吵了。专心玩游戏吧！', '怎么又断线了，网络怎么这么差啊！', '不要走，决战到天亮！', '底牌亮出来绝对吓死你！', '风水轮流转，底裤都输光！', '看我通杀全场，这些钱都是我的！', '不好意思啊，我要离开一会！'].indexOf(data.msg);
				Global.AudioManager.playSound('Game/ChatAudio/' + ((user.userInfo.sex == 0)? 'man/':'woman/') +index);
				label.active = true;
				label.getComponent(cc.Label).string = data.msg;
				this.scheduleOnce(() => {
					node.width = label.width+50;
					node.height = 58;
				}, 0);
				node.active = true;
				node.stopAllActions();
				node.runAction(cc.sequence(
					cc.delayTime(2),
					cc.callFunc(() => {
						node.active = false;
					})
				));
			}
		}
	},

	onDestroy: function () {
		Global.MessageCallback.removeListener('RoomMessagePush', this);
		Global.MessageCallback.removeListener('GameMessagePush', this);
		Global.MessageCallback.removeListener('ReConnectSuccess', this);
	},
});
